package top.lywivan.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import top.lywivan.common.pojo.Question;
import top.lywivan.search.mapper.SearchQuestionMapper;
import top.lywivan.search.service.SearchQuestionService;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Service
public class SearchQuestionServiceImpl extends ServiceImpl<SearchQuestionMapper, Question> implements SearchQuestionService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    @Transactional
    public void addQuestion(Question question) {
        if (question!=null){
            this.save(question);
        }
        //System.out.println(question.getId());

        IndexRequest indexRequest = new IndexRequest("question");
        if (question!=null){
            indexRequest.source(JSON.toJSONString(question), XContentType.JSON).id(question.getId()+"");
        }
        try {
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
